package parser_antlr4.doris;

import cn.hutool.core.util.StrUtil;
import constant.SQLParserConstants;
import exception.SQLParseException;
import domain.Table;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CodePointCharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import parser_antlr4.ErrorListener;
import parser_antlr4.Parser;
import parser_antlr4.doris.antlr4.DorisLexer;
import parser_antlr4.doris.antlr4.DorisParser;

import java.util.List;

public class DorisSQLParser implements Parser {

  @Override
  public List<Table> parseCreateSQL(String SQL) throws SQLParseException {
    ErrorListener hiveErrorListener = new ErrorListener();
    CodePointCharStream cs = CharStreams.fromString(SQL);

    DorisLexer lexer = new DorisLexer(cs);
    lexer.addErrorListener(hiveErrorListener);

    CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
    DorisParser parser = new DorisParser(commonTokenStream);
    parser.addErrorListener(hiveErrorListener);

    ParseTree tree = parser.multiCreateTableStatement();
    String errorMsg = hiveErrorListener.getErrorMsg();
    if (StrUtil.isNotBlank(errorMsg)) {
      throw new SQLParseException(String.format(SQLParserConstants.SQL_SYNTAX_ERROR, errorMsg));
    }

    DorisSQLListener dorisSQLListener = new DorisSQLListener(commonTokenStream);
    ParseTreeWalker.DEFAULT.walk(dorisSQLListener, tree);
    return dorisSQLListener.getTableList();
  }
}
